<?php

namespace Xrfg\Api\Trading\Spot\Listeners;

use Xrfg\Api\Trading\Spot\Events\OrderCreatedEvent;
use Xrfg\Api\Trading\Spot\Events\OrderUpdatedEvent;
use Xrfg\Core\Trading\Spot\Models\Order;
use Xrfg\Api\Trading\Spot\Repositories\OrderBook;

class UpdateOrderBook
{
    public $orderBook;

    public function __construct(OrderBook $orderBook)
    {
        $this->orderBook = $orderBook;
    }

    public function handle($event)
    {
        /** @var Order $order */
        $order = $event->order;
        if (!$order->exists) {
            return;
        }

        if ($event instanceof OrderCreatedEvent) {
            $this->orderBook->add($order);

            return;
        }

        if ($event instanceof OrderUpdatedEvent) {
            // 订单完全成交或撤销后需从订单簿移除
            if (!in_array($order->status, [$order::STATUS_FILLED, $order::STATUS_CANCELED])) {
                return;
            }
            $this->orderBook->remove($order);

            return;
        }
    }
}
